package com.uniledger.exchange.model.api;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.uniledger.exchange.BuildConfig;
import com.uniledger.exchange.model.OkSingleton;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class Api {

    private Retrofit retrofit;

    private Api() {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").serializeNulls().create();
        retrofit = new Retrofit.Builder()
                .client(OkSingleton.getInstance().getClient())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(BuildConfig.API_HOST)
                .build();
    }

    private Retrofit getRetrofit() {
        return retrofit;
    }

    private static class ApiInstance {
        private static final Api INSTANCE = new Api();
    }

    public static Api getInstance() {
        return ApiInstance.INSTANCE;
    }

    /**
     * 根据传入的baseUrl，和api创建retrofit
     */
    private static <T> T createApi(Class<T> clazz) {
        return getInstance().getRetrofit().create(clazz);
    }

    public static ApiService getService() {
        return createApi(ApiService.class);
    }

}
